/**
 * @description 真实交易拆分
 * @author wangjianjun
 */

import React, { PropTypes, PureComponent, Fragment } from 'react';
import { PrimaryC, PrimaryGhostC, SecondHeaderC, TableC, NoQueryC, SecuritiesCodeC, codeType, InputNumberC } from '../../../../comps';
import { fixedNum } from '../../../../utils/utils';
import moment from 'moment';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Input, Button, message, Table, Divider, DatePicker, Select, Modal, Popconfirm } from 'antd';
import TransactionFlow from '../common/TransactionFlow';
import ProductYield from '../common/ProductYield';
import CfModal from '../common/CfModal';
import ExportDataC from './exportDataC';
import styles from '../index.less';
const confirm = Modal.confirm;
const FormItem = Form.Item;
import { connect } from 'dva';
import 'moment/locale/zh-cn';

@Form.create()
@connect(({ survivalManageM, dictionaryM, loading, globalM }) => ({
  survivalManageM,
  dictionaryM,
  loading: loading.effects['survivalManageM/getTradeList'],
  globalM,
}))
export default class TransactionSplit extends PureComponent {
  constructor(props) {
    super(props);
    this.sybj = null;
    this.ASSET_SPLIT_TRADEDIR_GP = [];
    this.ASSET_SPLIT_TRADEDIR_ZQ = [];
    this.ASSET_SPLIT_TRADEDIR_HG = [];
    this.state = {
      search: null,
      columns: [],
      dataSource: [],
      columns1: [],
      dataSource1: [],
      rowDataKey: null,
      title: '交易录入',
      visible: false,
      visible1: false,
      currentPage: 1,
      numInPage: 5000,
      selDataSoure: [],
      tradeMarket: null,
      disabled: true,
      tradingCode: null,
      exchangeCode: null,
      fullPrice: null,
      data: {},
      clickid: null,
      tradeDirType: [],
      timeChange: null,
      timestamp: null,
      buyRateRequired: false,
      buyRateDisabled: true,
      ASSET_SPLIT_TRADEDIR_GP: [],
      ASSET_SPLIT_TRADEDIR_ZQ: [],
      ASSET_SPLIT_TRADEDIR_HG: [],
      ASSET_SPLIT_TRADETYPE: [],
      queryItems: {
        securityType: 'gp,zq,jj,etf,lczr,fb,jyshg,yhjhg,xyshg,ck,',
      },
      productObj: {}, //弹窗的产品下拉 单资产 多资产
      assetType: undefined, //多资产-1  单资产-0
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    const {
      globalM: { dataDictionary: e },
    } = this.props;
    //没看到调用 这里的字典
    let ds = [];
    e &&
      e['SECURITY_POOL_ITEM_JYSTYPE'] &&
      e['SECURITY_POOL_ITEM_JYSTYPE'].forEach((element) => {
        ds.push({
          code: element.code,
          value: element.value,
        });
      });

    if (e && e['ASSET_SPLIT_TRADEDIR_GP']) {
      this.ASSET_SPLIT_TRADEDIR_GP = e['ASSET_SPLIT_TRADEDIR_GP'];
    }

    if (e && e['ASSET_SPLIT_TRADEDIR_ZQ']) {
      this.ASSET_SPLIT_TRADEDIR_ZQ = e['ASSET_SPLIT_TRADEDIR_ZQ'];
    }

    if (e && e['ASSET_SPLIT_TRADEDIR_HG']) {
      this.ASSET_SPLIT_TRADEDIR_HG = e['ASSET_SPLIT_TRADEDIR_HG'];
    }
    if (e && e['ASSET_SPLIT_TRADETYPE']) {
      this.setState({
        ASSET_SPLIT_TRADETYPE: e['ASSET_SPLIT_TRADETYPE'],
      });
    }
    this.setState({
      selDataSoure: ds,
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    //只要有id传过来，接请求新的数据，不要判断相等
    if (nextProps.args && this.props.args && nextProps.args.timestamp != this.props.args.timestamp) {
      this.getTableData(nextProps.args.id);
      this.setState({
        search: nextProps.args.id,
        timestamp: nextProps.args.timestamp,
        dataSource1: [],
        rowDataKey: null, //清空选中的交易信息
      });
    }
  }
  //获取拆分弹窗 手工拆分 产品代码的下拉
  getProductListByListId = (record, multiAsserts) => {
    const { dispatch } = this.props;
    const { productObj } = this.state;
    let params = {
      listId: this.state.search,
      multiAsserts,
    };
    if (record.tradeDir != 1) {
      //当方向为买入的时候aid传，卖出时传卖出资产的aid
      params.aid = record.aid;
    }
    dispatch({
      type: 'survivalManageM/getProductListByListId',
      payload: { ...params },
      callback: (data) => {
        if (data) {
          productObj[multiAsserts] = data;
          this.setState({
            productObj: { ...productObj },
          });
        } else {
          this.setState({
            productObj: {},
          });
        }
      },
    });
  };

  //查询交易信息表格数据
  getTableData = (search) => {
    const { dispatch } = this.props;
    const { currentPage, numInPage } = this.state;
    dispatch({
      type: 'survivalManageM/save',
      payload: {
        loading1: true,
      },
    });
    //列表数据
    dispatch({
      type: 'survivalManageM/getTradeList',
      payload: {
        listId: search ? search : this.state.search,
        currentPage: currentPage,
        numInPage: numInPage,
      },
      callback: (flag, res) => {
        dispatch({
          type: 'survivalManageM/save',
          payload: {
            loading1: false,
          },
        });
        if (res) {
          this.setState({
            columns: res.columns,
            dataSource: res.dataSource,
          });
        }
      },
    });

    //产品收益率第一层数据
  };

  //给其它组件调用,刷新数据
  getNewData = () => {
    this.getTableData();
    if (this.state.rowDataKey && this.state.data && this.state.rowDataKey == this.state.data.id) {
      //若有选中项等于拆分项 则查询拆分后的交易流水
      this.querySplitTrade();
    }
    this.setState({
      timestamp: new Date().getTime(),
    });
  };

  changeVisible = () => {
    this.setState({
      visible1: !this.state.visible1,
    });
  };

  //交易录入增加
  add = () => {
    this.props.tradeAdd();
  };
  //获取该真实流水是多资产还是单资产
  getAssetType = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'survivalManageM/getAssetType',
      payload: {
        rid: record.id,
      },
      callback: (res) => {
        if (res && res.code == 0) {
          var status = res.data ? res.data.multiAsserts : ''; //多资产-1  单资产-0
          this.setState(
            {
              assetType: this.state.data.allocStatus == '1' ? status : undefined, //状态
              visible1: true,
            },
            () => {
              this.getProductListByListId(record, 0); //获取手工拆分产品下拉
              this.getProductListByListId(record, 1); //获取手工拆分产品下拉
            },
          );
        } else {
          message.error(res ? res.msg : '获取资产类型失败！');
        }
      },
    });
  };

  //回退流水
  rollbackFlow = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'survivalManageM/rollbackSplitTrade',
      payload: {
        id: record.id,
      },
      callback: (flag, res) => {
        this.getNewData();
        if (this.state.clickid == record.id) {
          this.setState({
            dataSource1: [],
          });
        }
      },
    });
  };

  //拆分流水
  splitFlow = (record) => {
    this.setState(
      {
        data: record,
        timeChange: new Date().getTime(),
      },
      () => {
        this.getAssetType(record); //获取是否是多资产
      },
    );
  };

  //删除流水
  deleteFlow = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'survivalManageM/deleteFlow',
      payload: {
        id: record.id,
      },
      callback: (res) => {
        this.getNewData();
        if (this.state.clickid == record.id) {
          this.setState({
            dataSource1: [],
          });
        }
      },
    });
  };
  //查询拆分后的交易流水
  querySplitTrade = () => {
    const { rowDataKey } = this.state;
    this.props.dispatch({
      type: 'survivalManageM/getTransactionFlow',
      payload: {
        id: rowDataKey,
      },
      callback: (res) => {
        if (res) {
          this.setState({
            clickid: rowDataKey,
            columns1: [...res.columns],
            dataSource1: [...res.dataSource],
          });
        }
      },
    });
  };

  render() {
    const {
      loading,
      survivalManageM: { loading1 },
    } = this.props;
    const { search, rowDataKey, columns1, dataSource1, columns, dataSource } = this.state;
    const operate = {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      type: 'operate',
      fixed: 'right',
      width: 120,
      operates: [
        {
          title: '拆分',
          onClick: (record) => this.splitFlow(record),
          rules: {
            hide: { relation: 'or', items: [{ key: 'allocStatus', value: ['2'], relation: ['='] }] },
          },
        },
        {
          title: '回退',
          onClick: (record) => this.rollbackFlow(record),
          rules: {
            hide: { relation: 'or', items: [{ key: 'allocStatus', value: ['0', '2'], relation: ['='] }] },
          },
        },
        {
          title: '删除',
          onClick: (record) => this.deleteFlow(record),
          rules: {
            hide: { relation: 'or', items: [{ key: 'allocStatus', value: ['1', '2'], relation: ['='] }] },
          },
        },
      ],
    };

    if (columns && columns.length > 0 && columns[columns.length - 1].key != 'id') {
      columns.push(operate);
    }
    columns.map((item) => {
      if (item.key == 'secuName') {
        //设置省略 要不固定操作列显示会有问题
        item.ellipsis = true;
      }
      if (item.key !== 'id' && item.key !== 'secuName') {
        item.width = parseFloat((parseFloat(89 / (this.state.columns.length - 2)) * 2526) / 100);
      }

      if (item.key == 'tradeTotalNum') {
        item.type = 'number';
      }

      if (
        item.key == 'tradeAmount' ||
        item.key == 'tradePrice' ||
        item.key == 'enFareTotal' ||
        item.key == 'enFare1' ||
        item.key == 'enFare2' ||
        item.key == 'enFare3' ||
        item.key == 'enFare4' ||
        item.key == 'enFare5' ||
        item.key == 'enFare6' ||
        item.key == 'enFare7' ||
        item.key == 'enFeeJs2' ||
        item.key == 'enFeeJg'
      ) {
        item.type = 'money';
        if (item.key == 'tradePrice') {
          item.toFixed = 4;
        }
      }

      if (item.key == 'buyRate') {
        item.type = 'rate';
        item.toFixed = 4;
      }
    });

    return (
      <div>
        {search ? (
          <div>
            <div>
              <Row>
                <Col span={12}>
                  <div style={{ position: 'relative', top: '4px' }}>
                    <SecondHeaderC title='交易信息' />
                  </div>
                </Col>
                <Col style={{ textAlign: 'right' }} span={12}>
                  <PrimaryGhostC title='交易录入' style={{ marginBottom: '10px' }} onClick={() => this.add()} />
                </Col>
              </Row>
            </div>
            <TableC
              onRow={(record, index) => {
                return {
                  onDoubleClick: (e) => {
                    this.setState(
                      {
                        rowDataKey: record.id,
                      },
                      () => {
                        this.querySplitTrade();
                      },
                    );
                  },
                };
              }}
              rowClassName={(record) => {
                return this.state.rowDataKey && record.id == this.state.rowDataKey ? styles.row_select : '';
              }}
              columns={this.state.columns}
              dataSource={this.state.dataSource}
              loading={loading1}
              hidePage={true}
              scroll={{ x: 2526, y: 210 }}
            />
            <div style={{ marginTop: '20px', position: 'relative' }}>
              <SecondHeaderC title='拆分后的交易流水' />
              <ExportDataC rid={this.state.rowDataKey} />
            </div>
            <TransactionFlow type='1' columns={columns1} dataSource={dataSource1} />

            <div style={{ marginTop: '20px' }}>
              <SecondHeaderC title='产品收益率' />
            </div>
            <ProductYield id={search} timestamp={this.state.timestamp} />
            {this.state.visible1 && (
              <CfModal
                assetType={this.state.assetType}
                visible1={this.state.visible1}
                changeVisible={this.changeVisible}
                getNewData={this.getNewData}
                data={this.state.data}
                id={search}
                timeChange={this.state.timeChange}
                productObj={this.state.productObj}
              />
            )}
          </div>
        ) : (
          <NoQueryC title={'请选择系列产品'} />
        )}
      </div>
    );
  }
}
